<template>
	<div class="layout-pd">
		<zh-header-toolbar >
			<zh-button style="margin-left: 8px" v-if="state.infoFlag" button-type="add" @click="functionAdd">同级新增</zh-button>
			<zh-button style="margin-left: 8px" v-if="state.infoFlag" button-type="add" @click="childfunctionAdd">子级新增 </zh-button>
			<zh-button style="margin-left: 8px" v-if="state.infoFlag" button-type="save" @click="saveFunction">保存</zh-button>
			<zh-button style="margin-left: 8px" v-if="state.infoFlag" button-type="del" @click="deleteFunction">删除</zh-button>
			<zh-button style="margin-left: 8px" v-if="state.infoFlag" icon="ele-Refresh" type="warning" @click="clearFunctionCache">清除缓存</zh-button>
			<zh-button style="margin-left: 8px" v-if="state.routerFlag" button-type="add" @click="openRouterModel">关联路由 </zh-button>
		</zh-header-toolbar>
		<zh-row>
			<zh-col :span="8">
				<zh-card shadow="hover">
					<zh-tree
						ref="functionTreeRef"
						:funcCode="state.treeUrl"
						:moveUrl="state.treeMoveUrl"
						:resultFields="{ treeList: 'functionList' }"
						node-key="key"
						:height="isTagsview ? `calc(100vh - 142px)` : `calc(100vh - 108px)`"
						:props="{ label: 'title' }"
						@node-click="onFunctionTreeSelect"
					></zh-tree>
				</zh-card>
			</zh-col>
			<zh-col :span="16">
				<zh-card shadow="hover" :style="{ height: isTagsview ? `calc(100vh - 142px)` : `calc(100vh - 108px)` }">
					<el-tabs v-model="activeName" @tab-click="tabsChange" :stretch="true">
						<el-tab-pane label="基础信息" name="baseInfo">
							<function-form ref="functionPage" />
						</el-tab-pane>
						<el-tab-pane label="路由列表" name="routerList">
							<function-router-form ref="routerForm" :select-node="state.selectNode" :functionInfo="state.functionInfo"> </function-router-form>
						</el-tab-pane>
					</el-tabs>
				</zh-card>
			</zh-col>
		</zh-row>
	</div>
</template>

<script lang="ts" setup name="functionManager">
import FunctionForm from '@/views/system/config/function/component/FunctionForm.vue';
import FunctionRouterForm from '@/views/system/config/function/component/FunctionRouterForm.vue';
import { loop } from '@/utils/util';

//------------------定义子组件---------------------------
const activeName = ref('baseInfo');
const functionPage = ref();
const routerForm = ref();
const functionTreeRef = ref();

//------------------内部变量定义-------------------------
const state = reactive({
	description: '功能管理',
	// 基础信息操作按钮是否显示
	infoFlag: true,
	functionInfo: null as any,
	// 路由列表操作按钮是否显示
	routerFlag: false,
	// 功能树
	expandedKeys: [] as any[],
	selectNode: {} as any,
	searchValue: '',
	autoExpandParent: true,
	functionList: [],
	// 关联路由弹出框
	errors: [] as any[],
	treeUrl: $api.system.getFunctionTreeList.url,
	treeMoveUrl: $api.system.moveFunction.url,
});

const { isTagsview } = storeToRefs($store.theme);
const saveType = ref('edit');

//------------------定义调用方法-------------------------

function onFunctionTreeSelect(selectNode) {
	saveType.value = 'edit';
	state.selectNode = selectNode;
	if (selectNode) {
		if (state.infoFlag) {
			findFuncInfo();
		}
		if (state.routerFlag) {
			findFuncInfo();
		}
	}
}
function findFuncInfo() {
	if (state.selectNode) {
		const params = {
			funcId: state.selectNode.value,
		};
		setTimeout(() => {
			$http
				.post($api.system.getFunctionDetail.url, params)
				.then((res) => {
					state.functionInfo = res.result;
					// 赋值子组件信息
					functionPage.value.setInitDate(res.result);
				})
				.catch(() => {});
		}, 50);
	}
}

function tabsChange() {
	if (activeName.value === 'baseInfo') {
		findFuncInfo();
		state.infoFlag = true;
		state.routerFlag = false;
	} else if (activeName.value === 'routerList') {
		findFuncInfo();
		routerForm.value.findRouterList();
		state.infoFlag = false;
		state.routerFlag = true;
	}
}
function findFunctionTreeList() {
	const params = {
		searchText: state.searchValue,
	};
	setTimeout(() => {
		$http
			.post($api.system.getFunctionTreeList.url, params)
			.then((res) => {
				const list = res.result.functionList;
				list.forEach((item) => {
					item.isLeaf = item.leaf;
				});
				state.functionList = list;
				state.expandedKeys = res.result.expandedKeys;
			})
			.catch(() => {});
	}, 50);
}
function saveFunction() {
	//表单验证
	functionPage.value.form.validate((valid) => {
		if (valid) {
			const functionData: any = functionPage.value.functionInfo;
			if (functionData.logFlag) {
				functionData.logFlag = '1';
			} else {
				functionData.logFlag = '0';
			}
			if (functionData.rollbackFlag) {
				functionData.rollbackFlag = '1';
			} else {
				functionData.rollbackFlag = '0';
			}
			if (functionData.auditFlag) {
				functionData.auditFlag = '1';
			} else {
				functionData.auditFlag = '0';
			}
			if (functionData.spanRollbackFlag) {
				functionData.spanRollbackFlag = '1';
			} else {
				functionData.spanRollbackFlag = '0';
			}
			if (functionData.funcId) {
				setTimeout(() => {
					$http
						.post($api.system.editFunction.url, functionData)
						.then((res) => {
							$messageBox.success('修改成功', '提示');
							functionPage.value.setInitDate(res.result);

							//更新树节点信息
							state.selectNode.title = res.result.funcTitle;
							functionTreeRef.value.updateKeyChildren(state.selectNode.key, state.selectNode);
						})
						.catch(() => {});
				}, 10);
			} else {
				setTimeout(() => {
					$http
						.post($api.system.addFunction.url, functionData)
						.then((res) => {
							$messageBox.success('新增成功', '提示');
							const addNode = {
								key: res.result.funcId,
								title: res.result.funcTitle,
								isLeaf: res.result.isLeaf,
								parentKey: res.result.parentId,
							};
							if (saveType.value === 'childAdd') {
								//子集新增
								functionTreeRef.value.append(addNode, state.selectNode.key);
							} else {
								//同级新增
								functionTreeRef.value.insertBefore(addNode, state.selectNode.key);
							}
						})
						.catch(() => {});
				}, 10);
			}
		}
	});
}
function functionAdd() {
	if (state.functionInfo) {
		saveType.value = 'add';
		const params = {
			parentId: state.functionInfo.parentId,
			parentTitle: state.functionInfo.parentTitle,
			funcId: '',
			status: '1',
			publicFlag: '0',
			nodeType: '0',
			api: state.functionInfo.api,
			classPath: state.functionInfo.classPath,
			orderNo: state.functionInfo.orderNo,
			rate: state.functionInfo.rate,
		};
		functionPage.value.setInitDate(params);
	} else {
		$messageBox.warning('请先选择某一节点', '提示');
	}
}
function childfunctionAdd() {
	if (state.functionInfo) {
		const nodeType = state.functionInfo.nodeType;
		if (nodeType && nodeType === '1') {
			$messageBox.warning('节点类型是叶子，不能添加子节点', '提示');
		} else {
			saveType.value = 'childAdd';
			const params = {
				parentId: state.functionInfo.funcId,
				parentTitle: state.functionInfo.funcTitle,
				status: '1',
				publicFlag: '0',
				nodeType: '0',
				funcId: '',
				orderNo: '',
				rate: null,
			};
			let rate = state.functionInfo.rate;
			if (rate) {
				rate = rate + 1;
			} else {
				rate = 1;
			}
			params.rate = rate;
			functionPage.value.setInitDate(params);
		}
	} else {
		$messageBox.warning('请先选择某一节点', '提示');
	}
}
function deleteFunction() {
	if (state.functionInfo) {
		const params = {
			funcId: state.functionInfo.funcId,
		};
		setTimeout(() => {
			$http
				.post($api.system.deleteFunction.url, params)
				.then(() => {
					$messageBox.success('删除成功', '提示');
					const data = [...state.functionList];
					loop(data, state.functionInfo.funcId, (item, index, arr) => {
						arr.splice(index, 1);
					});
					state.functionList = data;
					state.selectNode = [];
					state.functionInfo = null;
					functionPage.value.setInitDate(null);
				})
				.catch(() => {});
		}, 100);
	} else {
		$messageBox.warning('请先选择需要删除的数据', '提示');
	}
}
function clearFunctionCache() {
	const params: any = {};
	if (state.functionInfo) {
		params.funcId = state.functionInfo.funcId;
	}
	setTimeout(() => {
		$http
			.post($api.system.clearFunctionCache.url, params)
			.then(() => {
				$messageBox.success('清除缓存成功', '提示');
			})
			.catch(() => {});
	}, 100);
}
function openRouterModel() {
	routerForm.value.openRouterModel();
}

//------------------初始化------------------------------
onMounted(() => {
  nextTick(()=>{
	  findFunctionTreeList();
  })
});
</script>
<style lang="less" scoped></style>
